package com.starhub.common.security.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * JWT工具类
 */
public class JWTUtils {

    //有效期为
    public static final Long JWT_TTL = 2 * 60 * 60 *1000L;// 60 * 60 *1000  一个小时
    private static final SecretKey SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    /**
     * 统一管理的白名单路径（建议按功能分类注释）
     */
    public static final String[] WHITELIST = {
            // 基础功能接口
            "/api/starhub/user/login",
            "/api/starhub/document/download/*",
            "/api/starhub/document/downloadWithToken/*",

            // Swagger 相关
            "/swagger-ui.html",
            "/swagger-resources/**",
            "/swagger-ui/**",
            "/swagger-ui/index.html",
            "/v3/api-docs/**",
            "/webjars/**",

            "/logo_d.png",
            "/vite.svg",
            "/",
            "/*.html",
            "/assets/**",
            "/public/**",
            "/static/**",
            "/assistant/**",

            // 静态资源
            "/gz/**",
            "/css/**",
            "/js/**",
            "/img/**",
            "/uploads/**",
            "/favicon.ico",
            "/vite.svg",

            // Druid 监控
            "/druid/**",

            // 测试接口
            "/test/**"
    };


    public static String createJWT(String subject) {
        return createJWT(subject,JWT_TTL);
    }

    public static String createJWT(String subject, Long ttlMillis) {
        return Jwts.builder()
                .setSubject(subject)
                .setIssuedAt(new Date())
                .setExpiration(ttlMillis != null ? new Date(System.currentTimeMillis() + ttlMillis) : null)
                .signWith(SECRET_KEY, SignatureAlgorithm.HS256)
                .compact();
    }

    /**
     * 解析
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(jwt)
                .getBody();
    }

}